/*

* Copyright (C) 2023, KylinSoft Co., Ltd.

*

* This program is free software; you can redistribute it and/or modify

* it under the terms of the GNU General Public License as published by

* the Free Software Foundation; either version 3, or (at your option)

* any later version.

*

* This program is distributed in the hope that it will be useful,

* but WITHOUT ANY WARRANTY; without even the implied warranty of

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

* GNU General Public License for more details.

*

* You should have received a copy of the GNU General Public License

* along with this program; if not, see <http://www.gnu.org/licenses/&gt;.

*

*/



#include "power.h"
#include "powermacrodata.h"

#include <QDebug>
#include <QDBusReply>
#include <QDBusConnection>
#include <QThread>
//#include <ukcc/widgets/switchbutton.h>

Power::Power()
    : mFirstLoad(true)
    , m_iface(new QDBusInterface(
          UKUI_UPOWER_SERVICE, UKUI_UPOWER_PATH, UKUI_UPOWER_INTERFACE, QDBusConnection::sessionBus()))
    , m_sysIface(new QDBusInterface(
          POWER_MANAGEMENT_SERVICE,
          POWER_MANAGEMENT_PATH,
          POWER_MANAGEMENT_INTERFACE_NAME,
          QDBusConnection::systemBus()))
{
    QTranslator *translator = new QTranslator(this);
    translator->load("/usr/share/ukui-power-manager/power-plugin/translations/" + QLocale::system().name());
    QApplication::installTranslator(translator);

    pluginName = tr("Power");
    pluginType = SYSTEM;
}

Power::~Power() {}

QString Power::plugini18nName()
{
    return pluginName;
}

int Power::pluginTypes()
{
    return pluginType;
}

QWidget *Power::pluginUi()
{
    // 需要加上这个判断标志位，否则每次点击都会新建一个QWidget(只加载一次)
    if (mFirstLoad) {
        widget = new QWidget;
        QStringList list;
        widget->setAttribute(Qt::WA_DeleteOnClose);
        const QByteArray styleID(STYLE_FONT_SCHEMA);
        const QByteArray id(SESSION_SCHEMA);
        const QByteArray iid(SCREENSAVER_SCHEMA);
        const QByteArray powerID(POWER_SCHEMA);
        if (QGSettings::isSchemaInstalled(id) && QGSettings::isSchemaInstalled(styleID)
            && QGSettings::isSchemaInstalled(iid)) {
            stylesettings = new QGSettings(styleID, QByteArray(), this);
            sessionsettings = new QGSettings(id, QByteArray(), this);
            screensettings = new QGSettings(iid, QByteArray(), this);
            settings = new QGSettings(powerID, QByteArray(), this);
            connect(stylesettings, &QGSettings::changed, [=](QString key) {
                if ("systemFont" == key || "systemFontSize" == key) {
                    retranslateUi();
                }
            });
        }
        InitUI(widget);
        initSearchText();
        isLidPresent();
        isHibernateSupply();
        isExitBattery();
        setupComponent();
        initCustomPlanStatus(list);
        setupConnect();
        resetui();
        mFirstLoad = false;
    }
    return widget;
}

bool Power::isEnable() const
{
    return true;
}

const QString Power::name() const
{
    return QStringLiteral("Power");
}

bool Power::isShowOnHomePage() const
{
    return true;
}

QIcon Power::icon() const
{
    return QIcon::fromTheme("system-shutdown-symbolic");
}

QString Power::translationPath() const
{
    return "/usr/share/ukui-power-manager/power-plugin/translations/%1.ts";
}

void Power::InitUI(QWidget *widget)
{
    // 整体布局
    QVBoxLayout *mverticalLayout = new QVBoxLayout(widget);
    mverticalLayout->setSpacing(8);
    mverticalLayout->setContentsMargins(0, 0, 0, 0);

    CustomTitleLabel = new TitleLabel(widget);

    mverticalLayout->addWidget(CustomTitleLabel);

    // 通用设置布局
    Powerwidget = new QFrame(widget);
    Powerwidget->setMinimumSize(QSize(550, 0));
    Powerwidget->setMaximumSize(QSize(16777215, 16777215));
    Powerwidget->setFrameShape(QFrame::Box);

    PowerLayout = new QVBoxLayout(Powerwidget);
    PowerLayout->setContentsMargins(0, 0, 0, 0);
    PowerLayout->setSpacing(0);

    mSleepPwdFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mSleepPwdFrame);

    QHBoxLayout *mSleepPwdLayout = new QHBoxLayout(mSleepPwdFrame);
    mSleepPwdLayout->setContentsMargins(16, 0, 16, 0);

    mSleepPwdLabel = new QLabel(mSleepPwdFrame);
    mSleepPwdLabel->setFixedSize(550, 60);

    mSleepPwdBtn = new KSwitchButton(mSleepPwdFrame);
    mSleepPwdBtn->setObjectName("sleepwaken");
    mSleepPwdBtn->setChecked(screensettings->get(SLEEP_ACTIVATION_ENABLED).toBool());

    mSleepPwdLayout->addWidget(mSleepPwdLabel);
    mSleepPwdLayout->addStretch();
    mSleepPwdLayout->addWidget(mSleepPwdBtn);

    PowerLayout->addWidget(mSleepPwdFrame);

    line_1 = setLine(Powerwidget);
    PowerLayout->addWidget(line_1);

    mWakenPwdFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mWakenPwdFrame);

    QHBoxLayout *mWakenPwdLayout = new QHBoxLayout(mWakenPwdFrame);
    mWakenPwdLayout->setContentsMargins(16, 0, 16, 0);

    mWakenPwdLabel = new QLabel(mWakenPwdFrame);
    mWakenPwdLabel->setFixedSize(550, 49);

    mWakenPwdBtn = new KSwitchButton(mWakenPwdFrame);
    mWakenPwdBtn->setObjectName("lockwaken");
    mWakenPwdBtn->setChecked(screensettings->get(CLOSE_ACTIVATION_ENABLED).toBool());

    mWakenPwdLayout->addWidget(mWakenPwdLabel);
    mWakenPwdLayout->addStretch();
    mWakenPwdLayout->addWidget(mWakenPwdBtn);

    PowerLayout->addWidget(mWakenPwdFrame);

    line_2 = setLine(Powerwidget);
    PowerLayout->addWidget(line_2);

    mPowerKeyFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mSleepPwdFrame);

    QHBoxLayout *mPowerKeyLayout = new QHBoxLayout(mPowerKeyFrame);
    mPowerKeyLayout->setContentsMargins(16, 0, 16, 0);

    mPowerKeyLabel = new QLabel(mPowerKeyFrame);
    mPowerKeyLabel->setFixedSize(550, 60);
    mPowerKeyLabel->hide();

    mPowerKeyComboBox = new QComboBox(mPowerKeyFrame);
    mPowerKeyComboBox->setObjectName("powerkey");
    mPowerKeyComboBox->setMinimumWidth(200);
    mPowerKeyComboBox->hide();

    mPowerKeyLayout->addWidget(mPowerKeyLabel);
    mPowerKeyLayout->addWidget(mPowerKeyComboBox);

    //PowerLayout->addWidget(mPowerKeyFrame);

    line_3 = setLine(Powerwidget);
    PowerLayout->addWidget(line_3);

    mCloseFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mCloseFrame);

    QHBoxLayout *mCloseLayout = new QHBoxLayout(mCloseFrame);
    mCloseLayout->setContentsMargins(16, 0, 16, 0);

    mCloseLabel = new QLabel(mCloseFrame);
    mCloseLabel->setFixedSize(550, 60);

    mCloseComboBox = new QComboBox(mCloseFrame);
    mCloseComboBox->setObjectName("close");
    mCloseComboBox->setMinimumWidth(200);

    mCloseLayout->addWidget(mCloseLabel);
    mCloseLayout->addWidget(mCloseComboBox);

    PowerLayout->addWidget(mCloseFrame);

    line_4 = setLine(Powerwidget);
    PowerLayout->addWidget(line_4);

    mSleepFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mSleepPwdFrame);

    QHBoxLayout *mSleepLayout = new QHBoxLayout(mSleepFrame);
    mSleepLayout->setContentsMargins(16, 0, 16, 0);

    mSleepLabel = new QLabel(mSleepFrame);
    mSleepLabel->setFixedSize(550, 59);

    mSleepComboBox = new QComboBox(mSleepFrame);
    mSleepComboBox->setObjectName("sleep");
    mSleepComboBox->setMinimumWidth(200);

    mSleepLayout->addWidget(mSleepLabel);
    mSleepLayout->addWidget(mSleepComboBox);

    PowerLayout->addWidget(mSleepFrame);

    line_5 = setLine(Powerwidget);
    PowerLayout->addWidget(line_5);

    mCloseLidFrame = new QFrame(Powerwidget);
    setFrame_Noframe(mCloseLidFrame);

    QHBoxLayout *mCloseLidLayout = new QHBoxLayout(mCloseLidFrame);
    mCloseLidLayout->setContentsMargins(16, 0, 16, 0);

    mCloseLidLabel = new QLabel(mCloseLidFrame);
    mCloseLidLabel->setFixedSize(550, 59);

    mCloseLidComboBox = new QComboBox(mCloseLidFrame);
    mCloseLidComboBox->setObjectName("closelid");
    mCloseLidComboBox->setMinimumWidth(200);

    mCloseLidLayout->addWidget(mCloseLidLabel);
    mCloseLidLayout->addWidget(mCloseLidComboBox);

    PowerLayout->addWidget(mCloseLidFrame);

    mverticalLayout->addWidget(Powerwidget);
    mItem = new QSpacerItem(20, 24, QSizePolicy::Fixed);
    mverticalLayout->addSpacerItem(mItem);

    PowerPlanTitleLabel = new TitleLabel(widget);
    mverticalLayout->addWidget(PowerPlanTitleLabel);

    PowerPlanwidget = new QFrame(widget);
    PowerPlanwidget->setMinimumSize(QSize(550, 0));
    PowerPlanwidget->setMaximumSize(QSize(16777215, 16777215));
    PowerPlanwidget->setFrameShape(QFrame::Box);


    powerPlan();
    batterySavingWidget();

    mverticalLayout->addWidget(PowerPlanwidget);
    mverticalLayout->addSpacing(24);

    BatteryPlanTitleLabel = new TitleLabel(Powerwidget);
    mverticalLayout->addWidget(BatteryPlanTitleLabel);

    BatterySavePlanTitleLabel = new TitleLabel(Powerwidget);
    mverticalLayout->addWidget(BatterySavePlanTitleLabel);

    mverticalLayout->addWidget(Batterywidget);
    mverticalLayout->addStretch();

    retranslateUi();
}

void Power::powerPlan()
{
    // 电源计划布局
    QVBoxLayout *PowerPlanLayout = new QVBoxLayout(PowerPlanwidget);
    PowerPlanLayout->setContentsMargins(0, 0, 0, 0);
    PowerPlanLayout->setSpacing(0);

    mPowerFrame = new QFrame(PowerPlanwidget);
    setFrame_Noframe(mPowerFrame);

    QHBoxLayout *mPowerLayout = new QHBoxLayout(mPowerFrame);
    mPowerLayout->setContentsMargins(16, 0, 16, 0);

    mPowerLabel = new QLabel(mPowerFrame);
    mPowerLabel->setFixedSize(550, 60);

    mPowerComboBox = new QComboBox(mPowerFrame);
    mPowerComboBox->setObjectName("powermode");
    mPowerComboBox->setMinimumWidth(200);

    mPowerLayout->addWidget(mPowerLabel);
    mPowerLayout->addWidget(mPowerComboBox);

    PowerPlanLayout->addWidget(mPowerFrame);

    line_7 = setLine(PowerPlanwidget);
    PowerPlanLayout->addWidget(line_7);

    mBatteryFrame = new QFrame(PowerPlanwidget);
    setFrame_Noframe(mBatteryFrame);

    QHBoxLayout *mBatteryLayout = new QHBoxLayout(mBatteryFrame);
    mBatteryLayout->setContentsMargins(16, 0, 16, 0);

    mBatteryLabel = new QLabel(mBatteryFrame);
    mBatteryLabel->setFixedSize(550, 59);

    mBatteryComboBox = new QComboBox(mBatteryFrame);
    mBatteryComboBox->setObjectName("batterymode");
    mBatteryComboBox->setMinimumWidth(200);

    mBatteryLayout->addWidget(mBatteryLabel);
    mBatteryLayout->addWidget(mBatteryComboBox);

    PowerPlanLayout->addWidget(mBatteryFrame);
}

void Power::batterySavingWidget()
{
    /* 电池节电计划
     * Batterywidget 为电池节电计划的主界面
     * BatteryLayout 纵向布局
     * mOpenBatterySaveFrame  mBatterySaveOpenLayout mBatterySaveLevel 开启节电模式选项
     */

    Batterywidget = new QFrame(widget);
    Batterywidget->setMinimumSize(QSize(550, 0));
    Batterywidget->setMaximumSize(QSize(16777215, 16777215));
    Batterywidget->setFrameShape(QFrame::Box);

    BatteryLayout = new QVBoxLayout(Batterywidget);
    BatteryLayout->setContentsMargins(0, 0, 0, 0);
    BatteryLayout->setSpacing(0);

    /********************************************************
    ************************开启节能模式***********************
    *********************************************************/
    mOpenBatterySaveFrame = new QFrame(Batterywidget);
    setFrame_Noframe(mOpenBatterySaveFrame);

    QHBoxLayout *mBatterySaveOpenLayout = new QHBoxLayout(mOpenBatterySaveFrame);
    mBatterySaveOpenLayout->setContentsMargins(16, 0, 16, 0);


    mBatterySaveLevel = new QLabel(mOpenBatterySaveFrame);
    mBatterySaveLevel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    mBatterySaveLevel->setText(tr("Open BatterySaving"));


    mOpenBatterySavingBtn = new KSwitchButton(mOpenBatterySaveFrame);
    mOpenBatterySavingBtn->setObjectName("OpenBatterySaving");
    mOpenBatterySavingBtn->setMinimumWidth(50);

    mBatterySaveOpenLayout->addWidget(mBatterySaveLevel);
    mBatterySaveOpenLayout->addWidget(mOpenBatterySavingBtn);

    BatteryLayout->addWidget(mOpenBatterySaveFrame);


    line_9 = setLine(Batterywidget);
    BatteryLayout->addWidget(line_9);


    /********************************************************
    *****************节电模式自动降低屏幕亮度********************
    *********************************************************/
    mAutoBrightnessFrame = new QFrame(Batterywidget);
    setFrame_Noframe(mAutoBrightnessFrame);

    QHBoxLayout *mAutoBrightnessLayout = new QHBoxLayout(mAutoBrightnessFrame);
    mAutoBrightnessLayout->setContentsMargins(16, 0, 16, 0);


    mAutoBrightnessLevel = new QLabel(mOpenBatterySaveFrame);
    mAutoBrightnessLevel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    mAutoBrightnessLevel->setText(tr("Auto Display BrightnessLevel"));


    mAutoBrightnessBtn = new KSwitchButton(mAutoBrightnessFrame);
    mAutoBrightnessBtn->setObjectName("mAutoBrightnessBtn");
    mAutoBrightnessBtn->setMinimumWidth(50);

    mAutoBrightnessLayout->addWidget(mAutoBrightnessLevel);
    mAutoBrightnessLayout->addWidget(mAutoBrightnessBtn);

    BatteryLayout->addWidget(mAutoBrightnessFrame);


    /********************************************************
    ***************电量低于%20自动开启节电模式*******************
    *********************************************************/

    mNoticeLFrame = new QFrame(Batterywidget);
    setFrame_Noframe(mNoticeLFrame);

    QHBoxLayout *mNoticeLayout = new QHBoxLayout(mNoticeLFrame);
    mNoticeLayout->setContentsMargins(16, 0, 16, 0);

    mNoticeLabel = new QLabel(mNoticeLFrame);
    mNoticeLabel->setFixedSize(60, 59);
    mNoticeLabel->setText(tr("Battery Lower than"));

    mNoticeComboBox = new QComboBox(mNoticeLFrame);
    mNoticeComboBox->setObjectName("noticesettings");
    mNoticeComboBox->setFixedWidth(85);

    mLowBatteryAutoSavingLebel = new QLabel(mNoticeLFrame);
    mLowBatteryAutoSavingLebel->setFixedSize(550, 59);
    mLowBatteryAutoSavingLebel->setText(tr("Open AutoSaving Mode"));

    mLowBatteryAutoSavingBtn = new KSwitchButton(mNoticeLFrame);
    mLowBatteryAutoSavingBtn->setObjectName("mLowBatteryAutoSavingBtn");
    mLowBatteryAutoSavingBtn->setFixedWidth(50);

    mNoticeLayout->addWidget(mNoticeLabel);
    mNoticeLayout->addWidget(mNoticeComboBox);
    mNoticeLayout->addWidget(mLowBatteryAutoSavingLebel);
    mNoticeLayout->addSpacerItem(new QSpacerItem(0,160,QSizePolicy::Expanding,QSizePolicy::Expanding));
    mNoticeLayout->addWidget(mLowBatteryAutoSavingBtn);



    BatteryLayout->addWidget(mNoticeLFrame);
}

void Power::retranslateUi()
{
    if (QLabelSetText(mSleepPwdLabel, tr("Require Password when sleep"))) {
        mSleepPwdLabel->setToolTip(tr("Require password when sleep"));
    }

    if (QLabelSetText(mWakenPwdLabel, tr("Password required when waking up the screen"))) {
        mSleepPwdLabel->setToolTip(tr("Password required when waking up the screen"));
    }

    if (QLabelSetText(mPowerKeyLabel, tr("Press the power button"))) {
        mPowerKeyLabel->setToolTip("Press the power button");
    }

    if (QLabelSetText(mCloseLabel, tr("Time to close display"))) {
        mCloseLabel->setToolTip(tr("Time to close display"));
    }

    if (QLabelSetText(mSleepLabel, tr("Time to sleep"))) {
        mSleepLabel->setToolTip(tr("Time to sleep"));
    }

    if (QLabelSetText(mCloseLidLabel, tr("Notebook cover"))) {
        mCloseLidLabel->setToolTip(tr("Notebook cover"));
    }

    if (QLabelSetText(mPowerLabel, tr("Using power"))) {
        mPowerLabel->setToolTip(tr("Using power"));
    }

    if (QLabelSetText(mBatteryLabel, tr("Using battery"))) {
        mBatteryLabel->setToolTip(tr("Using power"));
    }

}

void Power::resetui()
{
    //不存在盖子隐藏该项
    if (!isExitsLid) {
        mCloseLidFrame->hide();
        line_5->hide();
    }

    //不存在电池隐藏这些设置项
    if (!hasBat) {
        line_7->hide();
        mBatteryFrame->hide();
        BatteryPlanTitleLabel->hide();
        clearAutoItem(BatteryLayout);
        Batterywidget->hide();
    }
}

void Power::initSearchText()
{
    //~ contents_path /Power/General
    CustomTitleLabel->setText(tr("General"));
    //~ contents_path /Power/Select Powerplan
    PowerPlanTitleLabel->setText(tr("Select Powerplan"));
    //~ contents_path /Power/Battery saving plan
    BatteryPlanTitleLabel->setText((tr("Battery saving plan")));
}

void Power::setupComponent()
{
    // 合盖
    closeLidStringList << tr("nothing") << tr("blank") << tr("suspend") << tr("shutdown");
    mCloseLidComboBox->insertItem(0, closeLidStringList.at(0), "nothing");
    mCloseLidComboBox->insertItem(1, closeLidStringList.at(1), "blank");
    mCloseLidComboBox->insertItem(2, closeLidStringList.at(2), "suspend");
    mCloseLidComboBox->insertItem(3, closeLidStringList.at(3), "shutdown");
    if (isExitHibernate) {
        closeLidStringList << tr("hibernate");
        mCloseLidComboBox->insertItem(4, closeLidStringList.at(4), "hibernate");
    }

    //按下电源键时
    buttonStringList << tr("interactive") << tr("suspend") << tr("shutdown") << tr("hibernate");
    mPowerKeyComboBox->insertItem(0, buttonStringList.at(0), "interactive");
    mPowerKeyComboBox->insertItem(1, buttonStringList.at(1), "suspend");
    mPowerKeyComboBox->insertItem(2, buttonStringList.at(2), "shutdown");
    if (isExitHibernate) {
        mPowerKeyComboBox->insertItem(3, buttonStringList.at(3), "hibernate");
    }
    if (settings->get("buttonPower").toString() == "interactive") mPowerKeyComboBox->setCurrentIndex(0);
    if (settings->get("buttonPower").toString() == "suspend") mPowerKeyComboBox->setCurrentIndex(1);
    if (settings->get("buttonPower").toString() == "shutdown") mPowerKeyComboBox->setCurrentIndex(2);
    if (settings->get("buttonPower").toString() == "hibernate") mPowerKeyComboBox->setCurrentIndex(3);

    //关闭显示器
    closeStringList << tr("5min") << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("never");
    mCloseComboBox->insertItem(0, closeStringList.at(0), QVariant::fromValue(5));
    mCloseComboBox->insertItem(1, closeStringList.at(1), QVariant::fromValue(10));
    mCloseComboBox->insertItem(2, closeStringList.at(2), QVariant::fromValue(15));
    mCloseComboBox->insertItem(3, closeStringList.at(3), QVariant::fromValue(30));
    mCloseComboBox->insertItem(4, closeStringList.at(4), QVariant::fromValue(60));
    mCloseComboBox->insertItem(5, closeStringList.at(5), QVariant::fromValue(120));
    mCloseComboBox->insertItem(6, closeStringList.at(6), QVariant::fromValue(0));

    //睡眠
    sleepStringList << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("3h") << tr("never");
    mSleepComboBox->insertItem(0, sleepStringList.at(0), QVariant::fromValue(10));
    mSleepComboBox->insertItem(1, sleepStringList.at(1), QVariant::fromValue(15));
    mSleepComboBox->insertItem(2, sleepStringList.at(2), QVariant::fromValue(30));
    mSleepComboBox->insertItem(3, sleepStringList.at(3), QVariant::fromValue(60));
    mSleepComboBox->insertItem(4, sleepStringList.at(4), QVariant::fromValue(120));
    mSleepComboBox->insertItem(5, sleepStringList.at(5), QVariant::fromValue(180));
    mSleepComboBox->insertItem(6, sleepStringList.at(6), QVariant::fromValue(0));

    //电源计划
    PowerplanStringList << tr("Balance Model") << tr("Save Model") << tr("Performance Model");
    mPowerComboBox->insertItem(0, PowerplanStringList.at(0), "Balance Model");
    mPowerComboBox->insertItem(1, PowerplanStringList.at(1), "Save Model");
    mPowerComboBox->insertItem(2, PowerplanStringList.at(2), "Performance Model");

    BatteryplanStringList << tr("Balance Model") << tr("Save Model") << tr("Performance Model");
    mBatteryComboBox->insertItem(0, BatteryplanStringList.at(0), "Balance Model");
    mBatteryComboBox->insertItem(1, BatteryplanStringList.at(1), "Save Model");
    mBatteryComboBox->insertItem(2, BatteryplanStringList.at(2), "Performance Model");

    LowpowerStringList << tr("shutdown");

    //低电量通知
    for (int i = 1; i < 5; i++) {
        mNoticeComboBox->insertItem(i - 1, QString("%1%").arg(i * 10));
    }
}
void Power::setupConnect()
{
    connect(mSleepPwdBtn, &KSwitchButton::stateChanged, [=](bool checked) {
        screensettings->set(SLEEP_ACTIVATION_ENABLED, checked);
    });

    if (screensettings->keys().contains("closeActivationEnabled")) {
        connect(mWakenPwdBtn, &KSwitchButton::stateChanged, [=](bool checked) {
            screensettings->set(CLOSE_ACTIVATION_ENABLED, checked);
        });
    }

    connect(mPowerKeyComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        //        设置电源键
                settings->set(BUTTON_POWER_KEY, mPowerKeyComboBox->itemData(index));
    });

    connect(mSleepComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Q_UNUSED(index)
        int closeDisplayTime = mCloseComboBox->currentData(Qt::UserRole).toInt() * 60;
        int sleepComputerTime = mSleepComboBox->currentData(Qt::UserRole).toInt() * 60;
        if (0 == sleepComputerTime) {
            setConfigValue(SLEEP_COMPUTER_AC, -1);
            setConfigValue(SLEEP_COMPUTER_BATTERY, -1);
        } else {
            setConfigValue(SLEEP_COMPUTER_AC, QVariant(sleepComputerTime));
            setConfigValue(SLEEP_COMPUTER_BATTERY, QVariant(sleepComputerTime));
            if (sleepComputerTime < closeDisplayTime) {
                setConfigValue(SLEEP_DISPLAY_AC_KEY, QVariant(sleepComputerTime));
                setConfigValue(SLEEP_DISPLAY_BAT_KEY, QVariant(sleepComputerTime));
            }
        }
    });

    connect(mCloseComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Q_UNUSED(index)
        int closeDisplayTime = mCloseComboBox->currentData(Qt::UserRole).toInt() * 60;
        int sleepComputerTime = mSleepComboBox->currentData(Qt::UserRole).toInt() * 60;
        if (0 == closeDisplayTime) {
            setConfigValue(SLEEP_DISPLAY_AC_KEY, -1);
            setConfigValue(SLEEP_DISPLAY_BAT_KEY, -1);
        } else {
            setConfigValue(SLEEP_DISPLAY_AC_KEY, QVariant(closeDisplayTime));
            setConfigValue(SLEEP_DISPLAY_BAT_KEY, QVariant(closeDisplayTime));
            if (closeDisplayTime > sleepComputerTime) {
                setConfigValue(SLEEP_COMPUTER_AC, QVariant(closeDisplayTime));
                setConfigValue(SLEEP_COMPUTER_BATTERY, QVariant(closeDisplayTime));
            }
        }
    });

    connect(mCloseLidComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        setConfigValue(BUTTON_LID_AC, mCloseLidComboBox->itemData(index));
        setConfigValue(BUTTON_LID_BATTERY, mCloseLidComboBox->itemData(index));
    });

    connect(mPowerComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        if (index == 0) {
            setConfigValue(POWER_POLICY_AC, 1);
        } else if (index == 1) {
            setConfigValue(POWER_POLICY_AC, 2);
        } else {
            setConfigValue(POWER_POLICY_AC, 0);
        }
    });

    connect(mBatteryComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        if (index == 0) {
            setConfigValue(POWER_POLICY_BATTERY, 1);
        } else if (index == 1) {
            setConfigValue(POWER_POLICY_BATTERY, 2);
        } else {
            setConfigValue(POWER_POLICY_BATTERY, 0);
        }
    });

    connect(screensettings, &QGSettings::changed, [=]() {
        mSleepPwdBtn->blockSignals(true);
        mWakenPwdBtn->blockSignals(true);
        if (screensettings->keys().contains("sleepActivationEnabled")) {
            mSleepPwdBtn->setChecked(screensettings->get(SLEEP_ACTIVATION_ENABLED).toBool());
        }

        if (screensettings->keys().contains("closeActivationEnabled"))
            mWakenPwdBtn->setChecked(screensettings->get(CLOSE_ACTIVATION_ENABLED).toBool());
        mSleepPwdBtn->blockSignals(false);
        mWakenPwdBtn->blockSignals(false);
    });

    connect(mOpenBatterySavingBtn, &KSwitchButton::stateChanged, [=](bool checked) {
        setConfigValue(BATTERY_SAVER, (int)checked);
        qDebug()<<"BATTERY_SAVER"<<(int)checked;
    });

    connect(mAutoBrightnessBtn, &KSwitchButton::stateChanged, [=](bool checked) {
        setConfigValue(BATTERY_SAVER_BRIGHTNESS, checked);
        qDebug()<<"BATTERY_SAVER_BRIGHTNESS"<<checked;
    });

    connect(mLowBatteryAutoSavingBtn, &KSwitchButton::stateChanged, [=](bool checked) {
        setConfigValue(BATTERY_SAVER_AUTO, checked);
        qDebug()<<"BATTERY_SAVER_AUTO"<<checked;
    });


    QDBusConnection::sessionBus().connect(
        UKUI_UPOWER_SERVICE,
        UKUI_UPOWER_PATH,
        UKUI_UPOWER_INTERFACE,
        "PowerConfigChanged",
        this,
        SLOT(initCustomPlanStatus(QStringList)));
}

void Power::initCustomPlanStatus(QStringList list)
{
    if (mFirstLoad) {
        list << SLEEP_COMPUTER_AC << SLEEP_DISPLAY_AC_KEY << BUTTON_LID_AC << POWER_POLICY_AC << POWER_POLICY_BATTERY
             << CRITICAL_BATTERY << ACTION_CRITICAL_BATTERY << LOW_BATTERY << BATTERY_SAVER << BATTERY_SAVER_BRIGHTNESS <<BATTERY_SAVER_AUTO;
    }
    // 信号阻塞
    mPowerKeyComboBox->blockSignals(true);
    mCloseComboBox->blockSignals(true);
    mSleepComboBox->blockSignals(true);
    mCloseLidComboBox->blockSignals(true);
    mPowerComboBox->blockSignals(true);
    mBatteryComboBox->blockSignals(true);
    mNoticeComboBox->blockSignals(true);
    //    mPowerKeyComboBox->setCurrentIndex(mPowerKeyComboBox->findData(settings->get(BUTTON_POWER_KEY).toString()));
    //    if (settings->get(SLEEP_COMPUTER_AC_KEY).toInt() == -1) {
    if (-1 != list.indexOf(SLEEP_COMPUTER_AC)) {
        if (getPowerConfData("GetSleepComputerAc", t1.Int) == -1) {
            mSleepComboBox->setCurrentIndex(mSleepComboBox->findData(0));
        } else {
            mSleepComboBox->setCurrentIndex(
                mSleepComboBox->findData(getPowerConfData("GetSleepComputerAc", t1.Int) / FIXES));
        }
    }
    if (-1 != list.indexOf(SLEEP_DISPLAY_AC_KEY)) {
        if (getPowerConfData("GetSleepDisplayAc", t1.Int) == -1) {
            mCloseComboBox->setCurrentIndex(mCloseComboBox->findData(0));
        } else {
            mCloseComboBox->setCurrentIndex(
                mCloseComboBox->findData(getPowerConfData("GetSleepDisplayAc", t1.Int) / FIXES));
        }
    }
    if (-1 != list.indexOf(BUTTON_LID_AC)) {
        mCloseLidComboBox->setCurrentIndex(mCloseLidComboBox->findData(getPowerConfData("GetButtonLidAc", t1.Str)));
    }
    if (-1 != list.indexOf(POWER_POLICY_AC)) {
        if (1 == getPowerConfData("GetPowerPolicyAc", t1.Int)) {
            mPowerComboBox->setCurrentIndex(0);
        } else if (2 == getPowerConfData("GetPowerPolicyAc", t1.Int)) {
            mPowerComboBox->setCurrentIndex(1);
        } else {
            mPowerComboBox->setCurrentIndex(2);
        }
    }
    if (-1 != list.indexOf(POWER_POLICY_BATTERY)) {
        if (1 == getPowerConfData("GetPowerPolicyBat", t1.Int)) {
            mBatteryComboBox->setCurrentIndex(0);
        } else if (2 == getPowerConfData("GetPowerPolicyBat", t1.Int)) {
            mBatteryComboBox->setCurrentIndex(1);
        } else {
            mBatteryComboBox->setCurrentIndex(2);
        }
    }

    if (-1 != list.indexOf(BATTERY_SAVER)) {
        int batterysaver = getPowerConfData("GetBatterySaver", t1.Int) ;
        if (2 == batterysaver) {
            Batterywidget->setVisible(false);
            BatteryPlanTitleLabel->setVisible(false);
        } else {
            Batterywidget->setVisible(true);
            BatteryPlanTitleLabel->setVisible(true);
            mOpenBatterySavingBtn->setChecked((bool)batterysaver);
        }
    }

    if (-1 != list.indexOf(BATTERY_SAVER_BRIGHTNESS)) {
        qDebug()<<"GetBatterySaverBrightness"<<getPowerConfData("GetBatterySaverBrightness", t1.Bool);
        mAutoBrightnessBtn->setChecked((bool)getPowerConfData("GetBatterySaverBrightness", t1.Bool));
    }

    if (-1 != list.indexOf(BATTERY_SAVER_AUTO)) {
        qDebug()<<"GetBatterySaverAuto"<<getPowerConfData("GetBatterySaverAuto", t1.Bool);
        mLowBatteryAutoSavingBtn->setChecked(getPowerConfData("GetBatterySaverAuto", t1.Bool));
    }

    // 信号阻塞解除
    mPowerKeyComboBox->blockSignals(false);
    mCloseComboBox->blockSignals(false);
    mSleepComboBox->blockSignals(false);
    mCloseLidComboBox->blockSignals(false);
    mPowerComboBox->blockSignals(false);
    mBatteryComboBox->blockSignals(false);
    mNoticeComboBox->blockSignals(false);
}

void Power::isLidPresent()
{
    QDBusInterface *LidInterface = new QDBusInterface(
        "org.freedesktop.UPower",
        "/org/freedesktop/UPower",
        "org.freedesktop.DBus.Properties",
        QDBusConnection::systemBus(),
        this);

    if (!LidInterface->isValid()) {
        qDebug() << "Create UPower Lid Interface Failed : " << QDBusConnection::systemBus().lastError();
        return;
    }
    QDBusReply<QVariant> LidInfo;
    LidInfo = LidInterface->call("Get", "org.freedesktop.UPower", "LidIsPresent");
    isExitsLid = LidInfo.value().toBool();
}

void Power::isHibernateSupply()
{
    QDBusInterface *HibernateInterface = new QDBusInterface(
        "org.freedesktop.login1",
        "/org/freedesktop/login1",
        "org.freedesktop.login1.Manager",
        QDBusConnection::systemBus(),
        this);
    if (!HibernateInterface->isValid()) {
        qDebug() << "Create login1 Hibernate Interface Failed : " << QDBusConnection::systemBus().lastError();
        return;
    }
    QDBusReply<QString> HibernateInfo;
    HibernateInfo = HibernateInterface->call("CanHibernate");
    isExitHibernate = HibernateInfo == "yes" ? true : false;
}

bool Power::isExitBattery()
{
    /* 默认机器没有电池 */
    hasBat = false;
    QDBusInterface *brightnessInterface = new QDBusInterface(
        "org.freedesktop.UPower",
        "/org/freedesktop/UPower/devices/DisplayDevice",
        "org.freedesktop.DBus.Properties",
        QDBusConnection::systemBus(),
        this);
    if (!brightnessInterface->isValid()) {
        qDebug() << "Create UPower Interface Failed : " << QDBusConnection::systemBus().lastError();
        return false;
    }

    QDBusReply<QVariant> briginfo;
    briginfo = brightnessInterface->call("Get", "org.freedesktop.UPower.Device", "PowerSupply");

    if (briginfo.value().toBool()) {
        hasBat = true;
    }
    return hasBat;
}

bool Power::QLabelSetText(QLabel *label, QString string)
{
    bool is_over_length = false;
    QFontMetrics fontMetrics(label->font());
    int fontSize = fontMetrics.width(string);
    QString str = string;
    if (fontSize > (label->width() - 5)) {
        str = fontMetrics.elidedText(string, Qt::ElideRight, label->width());
        is_over_length = true;
    }
    label->setText(str);
    return is_over_length;
}

void Power::clearAutoItem(QVBoxLayout *mLyt)
{
    if (mLyt->layout() != NULL) {
        QLayoutItem *item;
        while ((item = mLyt->layout()->takeAt(0)) != NULL) {
            if (item->widget()) {
                item->widget()->setParent(NULL);
            }
            delete item;
            item = nullptr;
        }
    }
}

void Power::setFrame_Noframe(QFrame *frame)
{
    frame->setMinimumSize(QSize(550, 60));
    frame->setMaximumSize(QSize(16777215, 60));
    frame->setFrameShape(QFrame::NoFrame);
}

QFrame *Power::setLine(QFrame *frame)
{
    QFrame *line = new QFrame(frame);
    line->setMinimumSize(QSize(0, 1));
    line->setMaximumSize(QSize(16777215, 1));
    line->setLineWidth(0);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    return line;
}

template <typename data>
data Power::getPowerConfData(const QString name, data type)
{
    QDBusReply<data> reply = m_iface->call(name);
    qDebug() << "get data name:" << name << ", type:" << type << ", value:" << reply.value();
    if (reply.isValid()) {
        return reply.value();
    } else {
        qDebug() << "Power get power conf data error:" << QDBusConnection::sessionBus().lastError();
        return type;
    }
}

void Power::setConfigValue(const QString key, const QVariant value)
{
    QDBusVariant v1;
    QVariant v2;
    v1.setVariant(value);
    v2.setValue(v1);
    m_sysIface->call("SetPowerConfig", key, v2);
}
